package com.dmcb.common.business.utils;

import org.springframework.stereotype.Service;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileReader;
import java.io.IOException;

/**
 * created by 王勇 on 2018/8/23.
 */
@Service
public class TouTiaoSignatureUtil {

    public String getSignature( String userId, String time) throws IOException, ScriptException, NoSuchMethodException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        //String webappRoot = classpath.replaceAll("WEB-INF/classes/", "");

        String data = "";

        FileReader reader = new FileReader("/"+classpath+"signature.txt");   // 执行指定脚本
        engine.eval(reader);

        if (engine instanceof Invocable) {
            Invocable invoke = (Invocable) engine;    // 调用merge方法，并传入两个参数
            data = (String) invoke.invokeFunction("getSignature", userId, time, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
            System.out.println(data);
            reader.close();

        }
        return data;
    }

}
